using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Volo.Abp;

namespace MatrixServiceDiscovery.HttpApi.Host
{
    public class Program
    {
        public static async Task<int> Main(string[] args)
        {
            // 配置Serilog
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .MinimumLevel.Override("Volo.Abp", LogEventLevel.Warning)
                .MinimumLevel.Override("System", LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .WriteTo.Async(c => c.File("logs/matrix-service-discovery-.log", rollingInterval: RollingInterval.Day))
                .WriteTo.Async(c => c.Console())
                .CreateLogger();

            try
            {
                Log.Information("启动 Matrix Service Discovery Host");
                var builder = WebApplication.CreateBuilder(args);
                builder.Host.AddAppSettingsSecretsJson()
                    .UseAutofac()
                    .UseSerilog();

                await builder.Build().RunAsync();
                return 0;
            }
            catch (Exception ex)
            {
                if (ex is HostAbortedException)
                {
                    throw;
                }

                Log.Fatal(ex, "Matrix Service Discovery Host 启动失败!");
                return 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
    }
}